#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

class InetAddr
{
public:
    InetAddr(struct sockaddr_in &addr)
    {
        // 网络转主机
        _port = ntohs(addr.sin_port);
        char buffer[64];
        inet_ntop(AF_INET, &_addr.sin_addr, buffer, sizeof(buffer));
        _ip = buffer;
    }
    InetAddr(const string &ip, const uint16_t port)
        : _ip(ip),
          _port(port)
    {
        // 主机转网络
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(_port);
    }

    bool operator==(const InetAddr &in)
    {
        return _ip == in._ip && _port == in._port;
    }

    string StringAddr()
    {
        return _ip + "+" + to_string(_port) + "#";
    }

    uint16_t Port() { return _port; }
    string Ip() { return _ip; }
    const sockaddr_in &Addr() { return _addr; }

    ~InetAddr() {}

private:
    struct sockaddr_in _addr;
    string _ip;
    uint16_t _port;
};